package org.ch02.test00.demo08.myWork;

import org.ch02.test00.demo06.myWork.SqlGenerate;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Map;
import java.util.Set;

/**
 * @author CSY
 * @date 2025 - 03 - 19
 */
public class BeanUtil<T> {

    public T select4Bean(Class<T> beanClass, Map<String,Object> cond){
        T obj = null;
        //自动生成查询所有数据的SQL语句
        String sql = SqlGenerate.generateSelect(beanClass,cond);
        System.out.println(sql);
        try {

            //获取结果集
            ResultSet rs = DbUtil.executeQuery(sql.toString(), cond.values().toArray());

            while (rs.next()) {
                //获取构造方法对象
                Constructor<T> constructor = beanClass.getConstructor();
                //实例化
                obj = constructor.newInstance();
                //获取到所有的字段对象
                Field[] declaredFields = beanClass.getDeclaredFields();
                for (Field field : declaredFields) {
                    //设置字段的权限
                    field.setAccessible(true);
                    //得到字段的类型的Class对象
                    Class<?> typeClazz = field.getType();
                    //获取SQL中的字段值
                    Object sqlFiled = rs.getObject(field.getName());
                    //判断如果获取的数据值为null那么直接跳出本次循环，执行下一次循环
                    if (sqlFiled == null) {
                        continue;
                    }
                    if(typeClazz == Date.class){
                        //将获取到的值类型转换
                        LocalDateTime localDateTime = (LocalDateTime) sqlFiled;
                        Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
                        sqlFiled = date;
                    }
                    //使用字段对象自带的方法给指定字段设置值 - field.set(要赋值的对象,值)
                    field.set(obj, sqlFiled);

                }
            }
            return obj;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
